#include "dynamicobject.h"
#include "Engine2D/dxsprite.h"

map<const char*, Sprite*> DynamicObject::mSprite = map<const char*, Sprite*>();
int DynamicObject::numberObject = 0;

DynamicObject::DynamicObject()
{	
    ++numberObject; 
}

DynamicObject::DynamicObject(GameGraphic* pGraphic, const char* nameObj, float x, float y, int _layer)
{	
    ++numberObject;
    if (mSprite.find(nameObj) == mSprite.end())
    {	
        char path[100] = "Data\\Mario Sprites\\";
        strcat(path, nameObj);
        strcat(path, ".png");
        mSprite[nameObj] = new DXSprite(pGraphic, path, D3DCOLOR_XRGB(0, 0, 0), 1, 1);
    }
    pSprite = mSprite[nameObj];
    posX = x;
    posY = y;
    layer = _layer;
    originX = 0;
    originY = 0;
}

Rect DynamicObject::GetRectBound()
{	
    Rect bound = {posX, posY, posX + pSprite->GetWidth(), posY + pSprite->GetHeight()};
    return bound;
}

int DynamicObject::GetLayer()
{	
    return layer;
}

void DynamicObject::SetOrigin(float x, float y)
{	
    originX = x;
    originY = y;
    return;
}

void DynamicObject::Update(unsigned int gameTime)
{ }

void DynamicObject::Render(unsigned int gameTime)
{	
    if (pSprite != 0)
    {	
        pSprite->SetPosition(posX - originX, posY - originY);
        pSprite->Draw();
    }
    return;
}

DynamicObject::~DynamicObject()
{	
    --numberObject;
    if (numberObject == 0)
    {	
        for (map<const char*, Sprite*>::iterator i = mSprite.begin(); i != mSprite.end(); ++i)
            if ((*i).second != 0)
                delete (*i).second;
    }
}

bool DynamicObject::IsCollide(Rect a, Rect b)
{	
    float width = (a.right - a.left) + (b.right - b.left);
    float height = (a.bottom - a.top) + (b.bottom - b.top);
    float x = a.left;
    if (b.left < x) 
        x = b.left;
    float y = a.right;
    if (b.right > y)
        y = b.right;
    float widthBound = y - x;
    x = a.top;
    if (b.top < x)
        x = b.top;
    y = a.bottom;
    if (b.bottom > y)
        y = b.bottom;
    float heightBound = y - x;
    if ((widthBound < width) && (heightBound < height))
        return true;
    else
        return false;
}